//
//  LoginViewController.m
//  momo
//
//  Created by HappyMilk 02 on 2017/5/1.
//  Copyright © 2017年 tomi. All rights reserved.
//

#import "LoginViewController.h"
#import "PublicTool.h"
#import "LoginHeader.h"
#import "UserModel.h"
#import <CoreLocation/CoreLocation.h>

@interface LoginViewController ()<CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIView *view_xian;
@property (weak, nonatomic) IBOutlet UITextField *tf_username;
@property (weak, nonatomic) IBOutlet UITextField *tf_password;

@property (weak, nonatomic) IBOutlet UIButton *btn_sgin;
@property (weak, nonatomic) IBOutlet UIButton *btn_register;

@property (nonatomic, strong) CLLocationManager* locationManager;

@end


@implementation LoginViewController

- (void)initializeLocationService {
    // 初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    // 设置代理
    _locationManager.delegate = self;
    // 设置定位精确度到米
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    
    [_locationManager requestWhenInUseAuthorization];
    // 开始定位
    [_locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取城市
            NSString *address = [NSString stringWithFormat:@"%@,%@",placemark.locality,placemark.name];
            NSLog(@"%@",address);
            [[NSUserDefaults standardUserDefaults] setObject:address forKey:@"address"];
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[MyAdTools shareInstance] addBannerADView2VC:self atPositionY:__kheight-90];
    // Do any additional setup after loading the view.
    ADD_OBSERVER(self, @selector(onAppInfoLoadedCB:), NOTIFICATION_APP_INFO_LOADED, nil);
    
    _tf_username.placeholder = LOC_STR(@"Please enter username");
    _tf_password.placeholder = LOC_STR(@"Please enter password");
    [_btn_sgin setTitle:LOC_STR(@"Sign in") forState:UIControlStateNormal];
    [_btn_register setTitle:LOC_STR(@"Register") forState:UIControlStateNormal];
    
    [UserModel registerSubclass];
    
    [self initializeLocationService];
    
}
- (void)onAppInfoLoadedCB:(id)sender{
    [self showWXLoginBtnIfNeed];
}
- (void)showWXLoginBtnIfNeed{
    if([MPWeChat stander].m_needLogin){
        
        UIButton *btn = [[UIButton alloc] initWithFrame:(CGRect){__kwidth/2-40,self.view_xian.frame.origin.y+40,80,80}];
        [btn setImage:[UIImage imageNamed:@"wx_logo.png"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(wxLoginAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
}
- (void)wxLoginAction{
    QRCodeLoginViewController * qrCodeLoginViewController = [[QRCodeLoginViewController alloc]initWithNibName:@"QRCodeLoginViewController" bundle:nil];
    [self presentViewController:qrCodeLoginViewController animated:true completion:nil];
}



- (IBAction)signAction:(UIButton *)sender {
    
    if ([[MyAdTools shareInstance] showInterstitialWithVC:self]) {
        return;
    }

    NSString *username = _tf_username.text;
    NSString *password = _tf_password.text;
    
    if(username.length<6 || password.length <6 ){
        NSString *msg = LOC_STR(@"Please fill in the correct account or password！Your account and password must be more than 6！");
        SHOW_HUD_MESSAGE(msg);
        return;
    }
    
    SHOW_HUD(LOC_STR(@"logging in..."));
    [AVUser logInWithUsernameInBackground:username password:password block:^(AVUser *user, NSError *error) {
        HIDE_HUD
        if (user != nil) {
            [MPWeChat stander].m_isLogin = true;
            [self dismissViewControllerAnimated:true completion:nil];
            
            [[NSUserDefaults standardUserDefaults] setObject:user.objectId forKey:@"user_id"];
            
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"Hint" message:LOC_STR(@"login successful") delegate:nil cancelButtonTitle:LOC_STR(@"Confirm") otherButtonTitles:nil, nil];
            //[alertview show];
            
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"GameViewController"];
            [self.navigationController pushViewController:vc animated:YES];
            
            AVQuery *query = [AVQuery queryWithClassName:@"User_list"];
            [query whereKey:@"user_id" equalTo:user.objectId];
            [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                
                if (objects.count>0) {
                    
                }else{
                    UserModel *model = [[UserModel alloc] init];
                    model.user_name = user.username;
                    model.user_emotion = @"No thing";
                    model.user_id = user.objectId;
                    model.user_address = [[NSUserDefaults standardUserDefaults] objectForKey:@"address"];
                    AVFile *file = [AVFile fileWithData:UIImagePNGRepresentation([UIImage imageNamed:@"mine"])];
                    model.user_img = file;
                    [model saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                        NSLog(@"error --- %@",error);
                    }];
                }
            }];
            
        } else {
            SHOW_HUD_MESSAGE(LOC_STR(@"Username or password is wrong!"));
        }
        
    }];
}
- (IBAction)registerAction:(UIButton *)sender {
    
    if ([[MyAdTools shareInstance] showInterstitialWithVC:self]) {
        return;
    }
    
    if ([MPWeChat stander].m_needLogin) {
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"服务器维护暂时停用注册功能！老用户可正常登录！新用户请使用第三方登录！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
    }
    else{
        [self registerAction];
    }
}
//注册
- (void)registerAction{
    NSString *username = _tf_username.text;
    NSString *password = _tf_password.text;
    
    if(username.length<6 || password.length <6 ){
        NSString *msg = LOC_STR(@"Please fill in the correct account or password！Your account and password must be more than 6！");
        SHOW_HUD_MESSAGE(msg);
        return;
    }
    SHOW_HUD(@"Is registering...");
    AVUser *user = [AVUser user];// 新建 AVUser 对象实例
    user.username = username;// 设置用户名
    user.password =  password;// 设置密码
    
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        HIDE_HUD
        if (succeeded) {
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"" message:LOC_STR(@"Registration success!please sign in") delegate:nil cancelButtonTitle:LOC_STR(@"Confirm") otherButtonTitles:nil, nil];
            [alertview show];
            [self.navigationController popViewControllerAnimated:true];
        } else {
            SHOW_HUD_MESSAGE(@"Registration failed, user name may exist, please try again or return to login");
        }
        
        NSLog(@"%@",error);
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.tf_password resignFirstResponder];
    [self.tf_username resignFirstResponder];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
